package com.learn.filter;

import com.learn.bean.IpCount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: learn-parent
 * @description
 * @author: luffy
 * @create: 2020-09-18 09:49
 */
@Slf4j
@Component
public class MyFilter implements GlobalFilter, Ordered {
    private Map<String, IpCount> ipCountMap = new ConcurrentHashMap<>();

    @Override

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie token = cookies.getFirst("token");
        log.info("Cookie的值" + token);
        String path = request.getURI().getPath();

        if (token != null) {
            System.out.println("token不为空");
        } else {
            if (path.contains("/user/index")) {
                response.setStatusCode(HttpStatus.FORBIDDEN);
                String msg = "you do not having token";
                DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }
        //IP防爆刷
        String ip = request.getRemoteAddress().getHostString();
        IpCount ipCount = ipCountMap.get(ip);
        if (path.contains("/user/registry")) {
            if (ipCount != null) {
                if (ipCount.getExpire() > System.currentTimeMillis()) {
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    String msg = "you have registered frequently and your request has been refused! Please try again in a minute!";
                    DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
            }
            IpCount ipCount1 = new IpCount();
            ipCount1.setExpire(System.currentTimeMillis() + 60 * 1000);
            ipCountMap.put(ip, ipCount1);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
